import { MongoClient } from 'mongodb';
import { config } from 'dotenv';

config();

const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/ai_drawing';

async function seedTemplates() {
    console.log('Starting seed process...');
    console.log('Connecting to MongoDB:', MONGODB_URI);

    let client;
    try {
        client = await MongoClient.connect(MONGODB_URI);
        console.log('Successfully connected to MongoDB');

        const db = client.db();
        const collection = db.collection('workflowtemplates');

        console.log('Clearing existing data...');
        await collection.deleteMany({});
        console.log('Existing data cleared');

        console.log('Inserting new templates...');
        const templates = [
            {
                name: '人像写实风格',
                description: '生成写实风格的人像图片，适合用于创建逼真的人物照片',
                author: 'AI Drawing Team',
                thumbnail: '/default-template.jpg',
                workflow: {
                    nodes: {
                        prompt: {
                            type: 'text_prompt',
                            value: 'realistic portrait, high quality, 8k'
                        }
                    }
                },
                params: [
                    {
                        id: 'prompt',
                        name: '提示词',
                        type: 'string',
                        default: 'realistic portrait, high quality, 8k',
                        description: '用于生成图片的提示词'
                    }
                ],
                tags: ['portrait', 'realistic', 'photo'],
                category: 'portrait',
                isPublic: true,
                version: '1.0.0',
                stats: {
                    uses: 120,
                    likes: 45,
                    views: 500
                },
                createTime: new Date(),
                updateTime: new Date()
            },
            {
                name: '动漫风格',
                description: '生成动漫风格的图片，适合创建二次元插画',
                author: 'AI Drawing Team',
                thumbnail: '/default-template.jpg',
                workflow: {
                    nodes: {
                        prompt: {
                            type: 'text_prompt',
                            value: 'anime style, vibrant colors'
                        }
                    }
                },
                params: [
                    {
                        id: 'prompt',
                        name: '提示词',
                        type: 'string',
                        default: 'anime style, vibrant colors',
                        description: '用于生成图片的提示词'
                    }
                ],
                tags: ['anime', 'cartoon', 'illustration'],
                category: 'anime',
                isPublic: true,
                version: '1.0.0',
                stats: {
                    uses: 200,
                    likes: 80,
                    views: 800
                },
                createTime: new Date(),
                updateTime: new Date()
            },
            {
                name: '风景油画',
                description: '生成油画风格的风景图片，适合创建艺术感强的场景',
                author: 'AI Drawing Team',
                thumbnail: '/default-template.jpg',
                workflow: {
                    nodes: {
                        prompt: {
                            type: 'text_prompt',
                            value: 'oil painting landscape, masterpiece'
                        }
                    }
                },
                params: [
                    {
                        id: 'prompt',
                        name: '提示词',
                        type: 'string',
                        default: 'oil painting landscape, masterpiece',
                        description: '用于生成图片的提示词'
                    }
                ],
                tags: ['landscape', 'oil-painting', 'art'],
                category: 'landscape',
                isPublic: true,
                version: '1.0.0',
                stats: {
                    uses: 150,
                    likes: 60,
                    views: 600
                },
                createTime: new Date(),
                updateTime: new Date()
            }
        ];

        // 添加日志记录
        console.log('Preparing to insert templates:', templates.length);
        console.log('Sample template:', JSON.stringify(templates[0], null, 2));

        try {
            const result = await collection.insertMany(templates);
            console.log(`Successfully inserted ${result.insertedCount} templates`);

            // 验证插入的数据
            const count = await collection.countDocuments();
            console.log(`Total templates in database: ${count}`);

            const sample = await collection.findOne();
            console.log('Sample template from database:', JSON.stringify(sample, null, 2));
        } catch (error) {
            console.error('Error seeding templates:', error);
            throw error;
        }
    } catch (error) {
        console.error('Error during seed process:', error);
        throw error;
    } finally {
        if (client) {
            await client.close();
            console.log('Database connection closed');
        }
    }
}

// 添加更好的错误处理
seedTemplates()
    .then(() => {
        console.log('Seed process completed successfully');
        process.exit(0);
    })
    .catch(err => {
        console.error('Seed process failed:', err);
        process.exit(1);
    }); 